package com.xuyiwei.mayi.lock;

import org.I0Itec.zkclient.ZkClient;

/**
 * Created by xuyiwei on 2019/4/23.
 */
public abstract class ZookeeperAbstractLock implements Lock {
    // zk连接地址
    private static final String CONNECTSTRING = "127.0.0.1:2181";
    // 创建zk连接
    protected ZkClient zkClient = new ZkClient(CONNECTSTRING);

    protected static final String PATH = "/lock";



    public abstract boolean tryLock();

    public abstract void waitLock();


    @Override
    public void getLock() {
        if(tryLock()){
            System.out.println("获取锁成功");
        }else{
            waitLock();
            // 重新获取锁资源
            getLock();
        }
    }

    @Override
    public void unLock() {
        if(zkClient!=null){
            zkClient.close();
            System.out.println("释放锁资源...");
        }
    }
}
